<?php
namespace api\common\model;
use think\Db;
class Order extends \think\Model 
{
    protected $autoWriteTimestamp = true;
    protected $table = 'order';//预约表

    /**
     * 员工服务上门订单
     */
    public function staffServerDoorOrder($orderNumber,$shopId){
        $res = false;
        $date = getNowDate();
        $data['updtime'] = $date;//修改时间
        $data['status'] = 2;//状态
      
            // 开始服务
            $upd = Db::name($this->table)->where('orderNumber', $orderNumber)->where('shopId',$shopId)->update($data);
            return $upd;
    }
    /**
     * 员工服务门店订单
     */
    public function staffServiceOrder($orderNumber,$shopId,$staffId){
        $res = false;
        $date = getNowDate();
        $data['updtime'] = $date;//修改时间
        $data['status'] = 2;//状态
        $data['staffId'] = $staffId;
        Db::startTrans();
        $transStatus['code'] = 1;
        $transStatus['message'] = '';
        try{
            // 开始服务

            $selStatus = Db::name($this->table)->where('orderNumber', $orderNumber)->where('shopId',$shopId)->find();
           
            // 门店预约人员减少
           if($selStatus['status'] == 1){

                $upd =  Db::name($this->table)->where('orderNumber', $orderNumber)->where('shopId',$shopId)->update($data);
                if (!$upd) {
                    $transStatus['message'] = "开始服务失败";
                    throw new \Exception("开始服务失败");
                }

                $server_dec = Db::name('shop_server')->where('shopId',$shopId)->setDec('waitingServer');
                if (!$server_dec) {
                    $transStatus['message'] = "待服务减少失败";
                    throw new \Exception("待服务减少失败");
                }
            }else{
                $transStatus['message'] = "订单不可服务";
                throw new \Exception("订单不可服务");
            }
            $server_inc = Db::name('shop_server')->where('shopId',$shopId)->setInc('serveringNumbers');;
            
            if(!$server_inc){
                $transStatus['message'] = "服务中减少失败";
                throw new \Exception("服务中减少失败");
            }
            $transStatus['code'] = 0;
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            dump($e->getMessage());
            // 回滚事务
            Db::rollback();
        }
        return $transStatus;
    }


    /**
     * 员工取消服务门店订单
     */
    public function staffCServiceOrder($orderNumber,$shopId,$staffId){
        $date = getNowDate();
        $data['updtime'] = $date;//修改时间
        $data['status'] = 1;//状态
        $data['staffId'] = 0;
        Db::startTrans();
        $transStatus['code'] = 1;
        $transStatus['message'] = '';
        try{
            // 取消

            $selStatus = Db::name($this->table)->where('orderNumber', $orderNumber)->where('shopId',$shopId)->find();

            if($staffId != $selStatus['staffId']){
                $transStatus['message'] = '员工订单不匹配';
                throw new \Exception("员工订单不匹配");
            }

           
            // 门店预约人员增加
            if($selStatus['status'] == 2){

                $upd =  Db::name($this->table)->where('orderNumber', $orderNumber)->where('shopId',$shopId)->update($data);
                if (!$upd) {
                    $transStatus['message'] = '取消服务失败';
                    throw new \Exception("取消服务失败");
                }

                $server_dec = Db::name('shop_server')->where('shopId',$shopId)->setInc('waitingServer');
                if (!$server_dec) {
                    $transStatus['message'] = '增加等待中失败';
                    throw new \Exception("增加等待中失败");
                }
            }else{
                $transStatus['message'] = '订单不可服务';
                throw new \Exception("订单不可服务");
            }
            $server_inc = Db::name('shop_server')->where('shopId',$shopId)->setDec('serveringNumbers');;
            
            if(!$server_inc){
                $transStatus['message'] = '减少服务中失败';
                throw new \Exception("减少服务中失败");
            }
            $transStatus['code'] = 0;
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            $log = $e->getMessage();
            // 回滚事务
            Db::rollback();
        }
        return $transStatus;
    }
















     /**
     * 员工开始服务(上门订单,陌客订单)
     */
    public function staffServerStart($shopId){
        $server_inc = Db::name('shop_server')->where('shopId',$shopId)->setInc('serveringNumbers');;
        return $server_inc;
           
    }

     /**
     * 员工服务完成(上门订单,陌客订单)
     */
    public function staffServerEnd($shopId){
        $watNum =  Db::name('shop_server')->field('serveringNumbers')->where('shopid',$shopId)->find();
        if($watNum['serveringNumbers']>0){
            $server_inc = Db::name('shop_server')->where('shopId',$shopId)->setDec('serveringNumbers');;
        }else{
            $server_inc = true;
        }
        return $server_inc;
    }

     /**
     * 员工取消已接的单
     */
    public function staffcancelOrder($orderNumber,$shopId){
        $res = false;
        $date = getNowDate();
        $data['updtime'] = $date;//修改时间
        $data['staffId'] = 0;//员工id
        $data['status'] = 1;//订单状态
        $data['shopId'] = 0;//店铺id
        Db::startTrans();
        $transStatus = false;
        try{
            // 取消接单
            $upd =  Db::name($this->table)->where('orderNumber', $orderNumber)->update($data);
            if (!$upd) {
                throw new \Exception("取消接单失败");
            }
            $transStatus = true;
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            \think\Log::record($e->getMessage());
            // 回滚事务
            Db::rollback();
        }
        return $transStatus;
    }
    /**
     * 员工接单
     */
    public function staffTakeOrder($orderNumber,$staffId,$shopId){
        $res = false;
        $date = getNowDate();
        $data['updtime'] = $date;//修改时间
        $data['staffId'] = $staffId;//员工id
        $data['shopId'] = $shopId;//员工id
        $upd =  Db::name($this->table)->where('orderNumber', $orderNumber)->update($data);
        return $upd;
    }

    /**
     * 取消预约
     */
    public function cancelOrder($userId,$orderNumber){
        $res = false;
        $status = 6;
        $date = getNowDate();
        $data['updtime'] = $date;//修改时间
        $data['status'] = $status;//状态
        Db::startTrans();
        $transStatus = false;
        try{
            // 修改订单状态
            $upd =  Db::name($this->table)->where('orderNumber', $orderNumber)->where('userId',$userId)->update($data);
            // 修改成功?
            if (!$upd) {
                throw new \Exception("取消预约失败");
            }
            // 根据订单号查询门店
            $orderInfo = $this->order_info($orderNumber);
            $shopId = $orderInfo['shopId'];
            // 门店预约人员减少
            // 查询店的等待人数
            $watNum =  Db::name('shop_server')->field('waitingServer')->where('shopid',$shopId)->find();
            if($watNum['waitingServer']>0){
                $server = Db::name('shop_server')->where('shopid',$shopId)->setDec('waitingServer');
            }else{
                $server = true;
            }
            if (!$server) {
                throw new \Exception("门店预约人员减少失败");
            }
            $transStatus = true;
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
        //    return json(returnAjax(null,$e->getMessage(),-1));
            dump($e->getMessage());
            // 回滚事务
            Db::rollback();
        }
        return $transStatus;
    }

    /**
     * 预约门店订单
     */
    public function addOrderShop($data){
       
        Db::startTrans();
        $transStatus = false;
        try{
            $date = getNowDate();
            $no = 1;
            $maxOrderNo = Db::name($this->table)->field('Max(orderNo) as no')->where('to_days(addtime)','to_days(now()')->find();
            if($maxOrderNo['no']){
                $no = (int)$maxOrderNo['no']+1;
            }
           
            $data['orderNo'] = $no;

            $ordernumber = time().'2'.$data['userId'].random(2,1);//订单号
            $data['addtime'] = $date;//添加时间
            $data['updtime'] = $date;//修改时间
            $data['overTime'] = date('Y-m-d H:i:s',strtotime("+5 hours"));//过期时间
            $data['payStatus'] = 1;//支付状态
            $data['staffId'] = 0;//员工id
            $data['orderNumber'] = $ordernumber;
            $maxOrderNo = Db::query('select Max(orderNo) as nos from mj_order where to_days(addtime) = to_days(now()) and shopId ='.$data['shopId'].'  limit 1');
            $no = 1;
            if($maxOrderNo[0]['nos']){
                $no = (int)$maxOrderNo[0]['nos']+1;
            }
            $data['orderNo'] = $no;
            $data['userStatus'] = 2;
            $insert = Db::name($this->table)->insert($data);
            if($insert){
                $sel = Db::name($this->table)->where('orderNumber',$ordernumber)->find();
                if($sel){
                    // 添加等待服务人数
                    $addServerCount = Db::name('shop_server')->where('shopid',$data['shopId'])->setInc('waitingServer');
                    if (!$addServerCount) {
                        throw new \Exception("门店预约人员增加失败");
                    }
                    $transStatus = $sel;
                }
            }else {
                throw new \Exception("订单添加失败");
            }
           
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            $transStatus = $e->getMessage();
            // 回滚事务
            Db::rollback();
        }
        return $transStatus;
    }



     /**
     * 根据订单号获取订单信息
     */
    public function order_info($orderNumber){

        $res =Db::name($this->table)->where('orderNumber',$orderNumber)->find();
        return $res;
    }
    /**
     * 根据支付订单号获取订单信息
     */
    public function order_info_server($orderNumber){
        $res =Db::name($this->table)->where('orderNumberPay',$orderNumber)->find();
        return $res;
    }

    /**
     * 订单信息修改
     */
    public function orderUpd($orderNumber,$data){
        $res =Db::name($this->table)->where('orderNumber',$orderNumber)->update($data);
        return $res;
    }

    /**
     * 预约订单支付更改订单信息
     * 订单号,支付状态,第三方订单,支付时间,服务状态
     */
    // public function order_update_pay($out_trade_no,$payStatus,$wxorder,$payTime,$shopId){

    //     // 查询当天最大预约号
       
    //     $data['payStatus'] = $payStatus;
    //     $data['paytime'] = $payTime;
    //     $data['status'] = 1;
    //     $data['wxOrder'] = $wxorder;
    //     $transStatus = false;
    //     // 修改订单信息
    //     $orders = Db::name($this->table)->where('orderNumber', $out_trade_no)->update($data);
    //     return $orders;

    // }


    /**
     * 门店订单支付更改订单信息
     */
    public function upd_shop_pay($data,$orderNumber,$shopId,$has_subsidy,$userId){
        $transStatus = false;
        Db::startTrans();
        try{
            // 修改订单信息
            $orders = Db::name($this->table)->where('orderNumberPay', $orderNumber)->update($data);
            if (!$orders) {
                throw new \Exception("订单状态修改失败");
            }
            // 门店预约人员减少

            // $watNum =  Db::name('shop_server')->field('waitingServer')->where('shopid',$shopId)->find();
            // if($watNum['waitingServer']>0){
            //     $server = Db::name('shop_server')->where('shopid',$shopId)->setDec('waitingServer');
            //     if (!$server) {
            //         throw new \Exception("门店预约人员减少失败");
            //     }
            // }
            if($has_subsidy){
                $user = Db::name('users')->where('userId',$userId)->setDec('vipNum');
                if (!$user) {
                    throw new \Exception("减少补贴次数失败");
                }
            }
            $transStatus = true;
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            \think\Log::record($e->getMessage());
            setLog($e->getMessage().'门店'.$orderNumber,'orderPay');
            // 回滚事务
            Db::rollback();
        }
        return $transStatus;
    }

    /**
     * 上门订单支付完成修改信息
     */
    public function upd_door_pay($data,$orderNumber,$has_subsidy,$userId){
        $transStatus = false;
        Db::startTrans();
        try{
            // 修改订单信息
            $orders = Db::name($this->table)->where('orderNumberPay', $orderNumber)->update($data);
            if (!$orders) {
                throw new \Exception("订单状态修改失败");
            }

            if($has_subsidy){
                $user = Db::name('users')->where('userId',$userId)->setDec('vipNum');
                if (!$user) {
                    throw new \Exception("减少补贴次数失败");
                }
            }
            $transStatus = true;
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            \think\Log::record($e->getMessage());
            setLog($e->getMessage().'上门-moker'.$orderNumber,'orderPay');
            // 回滚事务
            Db::rollback();
        }
        return $transStatus;
    }


    /**
     * 根据userId获取美甲记录,status
     */
    public function selRecord($userId,$status,$page){

        $numbers = 20;
        // 当前页数
        $this_page = 1;
        if($page){
            $this_page = $page;
        }

        if($status){
            
            $res = Db::query('SELECT
                t1.orderNumber,
                t1.shopId,
                t1.discountMoney,
                t1.`status`,
                t1.orderNo,
                t1.commodityId,
                t1.type,
                t2.shopName,
                t3.orderTime,
                t3.orderAddress,
                t3.orderName,
                t3.orderPhone
            FROM
                mj_order AS t1
                LEFT JOIN mj_shop AS t2 ON t1.shopId = t2.shopId
                left join mj_appointment as t3 on t1.appointId = t3.appointId
                
                where  t1.userId ='.$userId.' and t1.status = '.$status.' order by t1.updtime limit '.($this_page-1)*$numbers.','.$numbers);
        }else{
            $res = Db::query('SELECT
                t1.orderNumber,
                t1.discountMoney,
                t1.`status`,
                t1.orderNo,
                t1.commodityId,
                t1.type,
                t2.shopName,
                t3.orderTime,
                t3.orderAddress,
                t3.orderName,
                t3.orderPhone
            FROM
                mj_order AS t1
                LEFT JOIN mj_shop AS t2 ON t1.shopId = t2.shopId
                left join mj_appointment as t3 on t1.appointId = t3.appointId
                
                where t1.`status` <> 0 and t1.userId ='.$userId.' order by t1.updtime limit '.($this_page-1)*$numbers.','.$numbers);
        }
        return $res;
    } 


    /**
     * 查看用户是否有预约
     */
    public function is_order($userId){
        $res = Db::query('SELECT
                id 
            FROM
                mj_order 
            WHERE
                `status` = 1 and type = 2 and overTime>now() and userId = '.$userId);
        return $res[0];
    }
    /**
     * 用户预约的店
     */
    public function ordering($userId){
        $res = Db::query('SELECT
                shopId,orderNumber
            FROM
                mj_order 
            WHERE
                `status` = 1 and overTime>now() and type = 2 and userId = '.$userId);
        return $res[0];
    }

    /**
     * 上门订单列表
     */
    public function orderListDoor($staffId,$status,$page){
        if($status == 0){
            $staffId = 0;
        }
        $numbers = 20;
        // 当前页数
        $this_page = 1;
        if($page){
            $this_page = $page;
        }
        $res = Db::query('SELECT
            t1.id,
            t1.commodityId,
            t1.orderNumber,
            t2.orderName,
            t2.orderPhone,
            t2.orderTime,
            t2.orderAddress,
            t1.userId,
            t3.userPhoto
        FROM
            mj_order AS t1
            LEFT JOIN mj_appointment AS t2 on t1.appointId = t2.appointId
            LEFT JOIN mj_users as t3 on t1.userId = t3.userId
        
        where t1.staffId = '.$staffId.' and  t1.type= 1 and t1.status < 3 limit '.($this_page-1)*$numbers.','.$numbers);
      
        return $res;
    }
    
    /**
     * 到店订单列表
     * 
     */
    public function orderListShop($shopId,$page){
        $numbers = 20;
        // 当前页数
        $this_page = 1;
        if($page){
            $this_page = $page;
        }
        $res = Db::query('SELECT
            t1.orderNumber,
            t1.shopId,
            t1.orderNo,
            t2.userName,
            t2.userPhoto,
            t2.trueName,
            t1.userId
        FROM
            mj_order AS t1  LEFT JOIN mj_users  AS t2 ON t1.userId = t2.userId 
        
         where
        to_days(t1.addtime) = to_days(now()) and t1.overTime>now() and  t1.type = 2 AND t1.STATUS = 1  AND t1.shopId = '.$shopId.' 
        
        limit '.($this_page-1)*$numbers.','.$numbers);
        return $res;
    }
   

    /**
     * 陌客现金支付订单
     */
    public function mokerXjOrder($data){
        $ordernumber = time().'2'.$data['StaffId'].random(2,1);//订单号
        $data['orderNumber'] = $ordernumber;
        $res = Db::name('order')->insert($data);
        return $res;
    }

    /**
     * 陌客生成订单
     */
    public function mokerCOrder($data){
        $res = false;
        $ordernumber = time().'2'.$data['StaffId'].random(2,1);//订单号
        $data['orderNumber'] = $ordernumber;
        $inser = Db::name('order')->insert($data);
        if($inser){
            $res['orderNumber'] = $ordernumber;
        }
        return $res;
    }
    /**
     * 员工二维码收款订单修改
     */
    public function staffSQrcode($data,$orderNumber){
        $date = getNowDate();
        $data['updtime'] = $date;//修改时间
        $upd =  Db::name($this->table)->where('orderNumber', $orderNumber)->update($data);
        return $upd;
    }


    /**
     * 根据订单号查询订单状态
     */
    public function selStatusByNm($orderNumber){
      
      	 $upd  = Db::query('SELECT
                  t1.payStatus,
                  t1.status,
                  t1.reward,
                  t1.discountMoney,
                  t2.userName,
                  t2.trueName,
                  t2.userPhoto,
                  t2.userId,
                  t1.userStatus
                  FROM
                  mj_order AS t1
                  LEFT JOIN mj_users AS t2 ON t1.userId = t2.userId
                  where t1.orderNumber ='.$orderNumber);
        return $upd;
    }

    /**
     * 根据appointId获取订单信息
     */
    public function sel_info_appointId($appointId){
        $sel =  Db::name($this->table)->field('status')->where('appointId', $appointId)->find();
        return $sel;
    }


    // 根据店铺名获取当前的待服务人数
    public function getWatingNum($shopId){
        $res = 0;
        $sel = Db::query('SELECT
        count( orderNumber ) as num
            FROM
                mj_order 
            WHERE
                to_days(addtime) = to_days(now()) and overTime>now() and  type = 2 AND STATUS = 1  AND shopId = '.$shopId);
    if($sel){
        $res = $sel[0]['num'];
    }
    return $res;
    }
}
